package middleware

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"github.com/spf13/cast"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

const (
	ctxKeyUser  = "CtxKeyUser"
	ctxKeyToken = "ctxKeyToken"
)

const JwtSecret = "rn13jUwFP2pYFzq2ORVD"
const bearerLength = len("Bearer ")

func VerifyToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			token string
			param string
			// userId   string
			// operator string
		)
		//log.Println(c.ClientIP())
		if c.Request.Form == nil {
			//log.Println(c.Request.Form)
			err := c.Request.ParseMultipartForm(32 << 20)
			if err != nil {
				log.Println(err)
			}
		}
		//获取请求参数
		for k, v := range c.Request.Form {
			justString := strings.Join(v, "")
			param = param + "/" + k + "/" + justString
		}
		//请求token
		authorization := c.Request.Header.Get("Authorization")
		// log.Println(authorization)
		if authorization == "" {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"code": 201,
				"msg":  "校验码为空",
			})
			return
		}
		tokens := strings.Split(authorization, " ")
		if len(tokens) == 1 {
			token = tokens[0]
		} else if len(tokens) == 2 {
			token = tokens[1]
		}
		// if c.Request.Method == "POST" {
		// 	userId = c.PostForm("user_id")
		// 	operator = c.PostForm("user")
		// } else if c.Request.Method == "GET" {
		// 	userId = c.GetString("user_id")
		// 	operator = c.GetString("user")
		// }
		//解析验证token
		wxClaims, err := common.ParseToken(token)
		if err != nil {
			if err.Error() == "token is expired" {
				c.AbortWithStatusJSON(http.StatusOK, gin.H{"code": -1, "msg": "请重新登陆"})
				return
			}
			log.Println(err)
			c.AbortWithStatusJSON(http.StatusOK, gin.H{"msg": "token 解析失败"})
			return
		}
		common.SetCtxStudent(c, &wxClaims.User)
		common.SetCtxToken(c, token)
		//记录操作日志
		//log.Println(GlobalUnLogMap[c.FullPath()])
		if GlobalUnLogMap[c.FullPath()] == "" {
			oaLog := new(models.OaLog)
			//oaLog.Controller = MenuMap[c.FullPath()]
			oaLog.Controller = GlobalControllerMap[c.FullPath()]
			oaLog.Param = param
			oaLog.UserId = cast.ToInt(wxClaims.User.Id)
			oaLog.Operator = wxClaims.User.Name
			oaLog.Ip = c.ClientIP()
			oaLog.AddTime = time.Now()
			if err := oaLog.AddLog(); err != nil {
				log.Println(err)
			}
		}
		//c.Set("school_id", school_id)
		//c.Set("institution_code", institution_code)
		c.Next()
	}
}
